<template>
  <view>
    <button @click="onClickAdd">增加对比项</button>
    <button @click="onClickPrice">比价</button>
    <view>对比项排序：{{priceSort}}</view>
    <view class="box">
      <view v-for="(item,index) in priceArr" :key="index">
        <h3>对比项{{index+1}}</h3>
        <view>
          总价
          <input class="uni-input" placeholder="请输入总价" v-model="item.total" type="digit" @input='onBlurCalculate(item)' />
        </view>
        <view>
          数量
          <input class="uni-input" placeholder="请输入数量" v-model="item.num" type="digit" @input='onBlurCalculate(item)' />
        </view>
        <view>
          含量
          <input class="uni-input" placeholder="请输入含量" v-model="item.content" type="digit" @input='onBlurCalculate(item)' />
        </view>
        <view>
          单价
          <input class="uni-input" placeholder="请输入单价" disabled v-model="item.unitPrice" />
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        priceSort: '',
        priceArr: [{
          total: 0,
          num: 1,
          content: 1,
          unitPrice: 0,
          serial: 1
        }]
      };
    },
    methods: {
      // 添加项
      onClickAdd() {
        this.priceArr.push({
          total: 0,
          num: 1,
          content: 1,
          unitPrice: 0,
          serial: this.priceArr.length + 1
        })
      },
      // 比价
      onClickPrice() {
        this.priceArr.forEach(item => {
          item.unitPrice = item.total / (item.num * item.content)
        })
        let arr = [...this.priceArr]
        arr.sort((a, b) => {
          if (a.unitPrice && b.unitPrice) {
            return a.unitPrice - b.unitPrice
          }
        })
        if (arr.length == 0) return
        let str = ''
        arr.forEach((item, index) => {
          if (index != arr.length - 1) {
            str = str + `对比项${item.serial}(${(item.unitPrice - arr[index+1].unitPrice).toFixed(4)}) => `
          } else {
            str = str + `对比项${item.serial}`
          }
        })
        this.priceSort = str
      },
      // 计算单价
      onBlurCalculate(item) {
        if(!item.total || !item.num || !item.content) return
        console.log(this.priceArr, 'priceArr');
        console.log(item);
        item.unitPrice = (item.total / (item.num * item.content)).toFixed(4)
      }
    }
  }
</script>

<style lang="scss">

</style>